package 字符串;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackageName: 电话号码的字母组合
 * @ClassName: LeetCode17
 * @Author: chen jinxu
 * @Date: 2023/3/12 9:08
 * 给定一个仅包含数字2-9的字符串，返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
 * 给出数字到字母的映射如下（与电话按键相同）。注意 1 不对应任何字母。
 * 输入：digits = "23"
 * 输出：["ad","ae","af","bd","be","bf","cd","ce","cf"]
 * 输入：digits = ""
 * 输出：[]
 * 输入：digits = "2"
 * 输出：["a","b","c"]
 * 0 <= digits.length <= 4
 * digits[i] 是范围 ['2', '9'] 的一
 */
public class LeetCode17 {
    public static void main(String[] args) {
        System.out.println(letterCombinations("23"));
        System.out.println(letterCombinations(""));
        System.out.println(letterCombinations("2"));
    }

    public static List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        int len = digits.length();
        if (len == 0) {
            return result;
        }
        Map<Character, String> map = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backTrack(result, map, digits, 0, new StringBuilder());
        return result;
    }

    private static void backTrack(List<String> result, Map<Character, String> map, String digits, int idex,
                                  StringBuilder stringBuilder) {
        if (idex == digits.length()) {
            result.add(stringBuilder.toString());
        } else {
            String characters = map.get(digits.charAt(idex));
            for (int i = 0; i < characters.length(); i++) {
                stringBuilder.append(characters.charAt(i));
                backTrack(result, map, digits, idex + 1, stringBuilder);
                stringBuilder.deleteCharAt(idex);
            }
        }
    }
}
